import React, { useEffect, useState } from 'react';
import { Col, Icon, Row, InputNumber, Form } from 'antd';
import AxCard from '@/components/AxBase/AxCard';
import { AxButton, AxButtonOk } from '@/components/AxBase';
import { AxTable } from '@/components/AxList';
import { AxInput, AxPlaceHolder, AxSelectSearch } from '@/components/AxForm/AxFormItem';
import IconFont from '@/assets/iconfont';
import { router } from 'umi';
import { axconst } from '@/shared/axconst';
import { axurl } from '@/shared/axurl';
import { axhttp } from '@/shared/axhttp';
import { axhelper } from '@/shared/axhelper';

const url = axurl.material.order;
const { getX, getDataX, postFormX } = axhttp;
const Index: React.FC<any> = props => {
    const { form, location } = props;
    const { orderIds } = location && location.query && location.query || {};
    const [data, setData] = useState<any>([]);
    const [labs, setLabs] = useState<any>([]);
    const [addrs, setAddrs] = useState<any>([]);
    const [loading, setLoading] = useState(false);
    const [submiting, setSubmiting] = useState(false);
    const [addrLoading, setAddrLoading] = useState(false);
    const [labLoading, setLabLoading] = useState(false);

    useEffect(() => {
        handleReadGoods();
        handleReadLab();
    }, []);

    /** 获取商品列表 */
    const handleReadGoods = (p: any = {}) => {
        setLoading(true);
        return getX(url.readDetail, {
            orderIds: [orderIds],
            ...p,
        }).then((res: any) => {
            setData(res.data);
            return Promise.resolve(res.data);
        }).finally(() => {
            setLoading(false);
        });
    }

    /** 获取采购主体 */
    const handleReadLab = () => {
        setLabLoading(true);
        return getDataX(url.readLabs).then((res: any) => {
            setLabs(axhelper.transToStandardData(res.list, 'labId', 'name'));
        }).finally(() => {
            setLabLoading(false);
        });
    }

    /** 获取地址 */
    const handleChangeLab = (labId: any) => {
        setAddrLoading(true);
        return getDataX(url.readAddrs, {
            labId,
        }).then((res: any) => {
            setAddrs(axhelper.transToStandardData(res.list, 'address', 'address'));
        }).finally(() => {
            setAddrLoading(false);
        });
    }

    const columns = [
        {
            dataIndex: 'image',
            width: 110,
            render: (val: any) => {
                return (<img src={val && val !== '' && val || '/img/nopic.jpg'} style={{ height: 110, width: 110 }} />);
            },
        },
        {
            width: axconst.width.longx,
            render: (val: any, record: any) => {
                return (
                    <div style={{ marginLeft: 16 }}>
                        <h4 className='ant-list-item-meta-title'>
                            {record.name}
                        </h4>
                        <div className='ant-list-item-meta-description'>
                            {record.eName}
                        </div>
                    </div>
                );
            },
        },
        {
            width: axconst.width.long,
            render: (val: any, record: any) => {
                return (
                    <div>
                        <div>
                            <span>产品规格：{record.productSpec}</span>
                        </div>
                        <div>
                            <span>别名：{record.alias}</span>
                        </div>
                        <div>
                            <span>分子式：{record.formula}</span>
                        </div>
                        <div>
                            <span>纯度：{record.purity}</span>
                        </div>
                        <div>
                            <span>危险源：{record.dangerName && record.dangerName.length > 0 && record.dangerName.map((m: any) => (
                                <>
                                    <span className='ax-manager'>{m}</span>&nbsp;
                            </>
                            )) || '无'}
                            </span>
                        </div>
                    </div>
                );
            },
        },
        {
            width: axconst.width.long,
            render: (val: any, record: any) => {
                return (
                    <div>
                        <div>
                            <span>单价：￥{record.price}</span>
                        </div>
                        <div>
                            <span>库存：{record.stock}</span>
                        </div>
                        <div>
                            <span>管控：{record.controlLevel}</span>
                        </div>
                    </div>
                );
            },
        },
        {
            width: axconst.width.long,
            render: (val: any, record: any) => {
                return (
                    <div>
                        <div>
                            <span>包装：{record.packingUnit}</span>
                        </div>
                        <div>
                            <span>性状：{record.character}</span>
                        </div>
                        <div>
                            <span>销量：{record.saleAmount}</span>
                        </div>
                        <div>
                            <span>分类名称：{record.categoryName}</span>
                        </div>
                    </div>
                );
            },
        },
        {
            dataIndex: 'amount',
            width: 130,
            render: (val: any, record: any) => (
                <div onClick={e => e.stopPropagation()}>
                    <InputNumber
                        style={{ width: 124 }}
                        defaultValue={val}
                        min={1}
                        onBlur={(e) => handleBlur(e, record)}
                    />
                </div>
            ),
        },
    ];

    /** 修改购买量 */
    const handleBlur = (e: any, r: any) => {
        setData((old: any) => {
            old.forEach((i: any) => {
                i.products && i.products.forEach((j: any) => {
                    if (j.productId === r.productId) {
                        j.amount = e.target.value;
                    }
                });
            });

            return old.map((m: any) => ({
                ...m,
                products: [...m.products],
            }))
        });
    }

    /** 提交订单 */
    const handleSubmit = (fv: any) => {
        setSubmiting(true);
        const details: any[] = [];

        data.forEach((i: any) => {
            i.products && i.products.forEach((j: any) => {
                details.push({
                    detailId: j.detailId,
                    amount: j.amount,
                });
            });
        });
        return postFormX(url.create, null, {
            orderId: orderIds,
            ...fv,
            detailsJson: JSON.stringify(details)
        }).then(() => {
            router.push('/buyer/material/order/nocommit');
        }).finally(() => {
            setSubmiting(false);
        });
    }

    return (
        <>
            <div style={{ borderBottom: '2px solid #409eff' }}>
                <AxCard
                    style={{ marginBottom: '15px', height: '100%', width: 1390, margin: '24px auto' }}
                    bodyStyle={{ padding: 0 }}
                >
                    <Row>
                        <Col span={24}>
                            <div style={{ fontSize: 22 }}><Icon type="shopping-cart" />&nbsp;订单结算</div>
                        </Col>
                    </Row>
                </AxCard>
            </div>
            {data && data.map((m: any, idx: any) => (
                <AxCard
                    style={{ height: '100%', width: 1390, margin: '0 auto' }}
                    bodyStyle={{ paddingLeft: 0, paddingRight: 0, paddingBottom: 0 }}
                    key={idx}
                >
                    <AxTable
                        title={() => m.supplierName}
                        size='default'
                        bordered={false}
                        showHeader={false}
                        loading={loading}
                        columns={columns}
                        checkboxModel={false}
                        data={{
                            list: m.products && m.products.map((i: any) => ({
                                ...i,
                                id: i.productId,
                            })),
                            success: true,
                        }}
                    />
                </AxCard>
            ))}
            <AxCard
                style={{ margin: '15px auto', width: 1390 }}
                bodyStyle={{ padding: 0 }}
            >
                <Row>
                    <Col span={16}>
                        <Row>
                            <Col span={12}>
                                <AxSelectSearch
                                    form={form}
                                    label="采购主体"
                                    field="labId"
                                    data={labs}
                                    onChange={handleChangeLab}
                                    required
                                />
                            </Col>
                            <Col span={12}>
                                <AxPlaceHolder />
                            </Col>
                            <Col span={12}>
                                <AxSelectSearch
                                    form={form}
                                    label="地址"
                                    field="address"
                                    data={addrs}
                                    // loading={addrLoading}
                                    required
                                />
                            </Col>
                            <Col span={12}>
                                <AxPlaceHolder />
                            </Col>
                            <Col span={12}>
                                <AxInput
                                    form={form}
                                    label="联系人"
                                    field="linkManName"
                                    required
                                />
                            </Col>
                            <Col span={12}>
                                <AxPlaceHolder />
                            </Col>
                            <Col span={12}>
                                <AxInput
                                    form={form}
                                    label="联系电话"
                                    field="linkPhone"
                                    pattern={axconst.valid.mobile}
                                    required
                                />
                            </Col>
                        </Row>
                    </Col>
                </Row>
            </AxCard>
            <AxCard
                height={55}
                style={{ margin: '0 auto', width: 1390 }}
                // bodyStyle={{ padding: 10, marginTop: 3, float: 'right' }}
                bodyStyle={{ padding: 0 }}
            >
                <Row>
                    <Col span={16}>
                        <div className='ant-modal-footer' style={{ borderTop: '0' }}>
                            <AxButtonOk icon={undefined} className='ax-no-class' type="primary" form={form} handleClick={handleSubmit} flag='continue'>
                                <IconFont type='iconsave' />确认支付下单
                            </AxButtonOk>
                        </div>
                    </Col>
                </Row>
            </AxCard>
        </>
    );
};

export default Form.create<any>()(Index);